﻿using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.TestManagement.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TestStepsEditor.Viewers.Data;

namespace TestStepsEditor.Actions
{
    internal class WorkItems
    {
        public static int New(string workItemType, SharedData data)
        {
            WorkItemType wiType = null;

            var projectUrl = new Uri(data.TfsProjectCollection.Uri.ToString());

            TfsTeamProjectCollection collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(projectUrl);

            var wiStore = (WorkItemStore) collection.GetService(typeof (WorkItemStore));

            if (workItemType == "T")
                wiType = wiStore.Projects["SolArc"].WorkItemTypes["Test Case"];
            else
            {
                if (workItemType == "S")
                    wiType = wiStore.Projects["SolArc"].WorkItemTypes["Shared Steps"];
            }

            var wi = new WorkItem(wiType) {Title = data.WorkItemAttributes.Name};

            if (data.WorkItemAttributes != null)
            {
                wi.AreaPath = data.WorkItemAttributes.Area;
                wi.IterationPath = data.WorkItemAttributes.IterationPath;
                wi.Description = data.WorkItemAttributes.Description;
                wi["Priority"] = data.WorkItemAttributes.Priority;
                if (wi.Fields.Contains("Start Release"))
                    wi["Start Release"] = data.WorkItemAttributes.StartRelease;
            }

            wi.Save();

            return wi.Id;
        }

        public static SharedData Save(SharedData data)
        {
            int workItemId;
            if (!Int32.TryParse(data.WorkItemID.ToString(), out workItemId))
                return null;
            if (data.TestWorkItem != null)
            {
                try
                {
                    if (data.TestWorkItem.WorkItem.Type.Name == "Shared Steps")
                    {
                        DialogResult result = MessageBox.Show(
                            @"Please ensure that the 'Domain Lead' has approved this change.  If so then click 'Yes' else click 'No'.",
                            @"Do you have approval?", MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Yes)
                        {
                        }
                        if (result == DialogResult.Cancel)
                        {
                            MessageBox.Show(@"Work Item was NOT saved.");
                            return data;
                        }
                        if (result == DialogResult.No)
                        {
                            MessageBox.Show(@"Work Item was NOT saved.");
                            return data;
                        }
                    }


                    data.TestWorkItem.Actions.Clear();
                    string directoryName = @"C:\TestCaseEditor\UploadFiles";
                    if (!Directory.Exists(directoryName))
                        Directory.CreateDirectory(@"C:\TestCaseEditor\UploadFiles");


                    int stepNumber = 0;
                    foreach (var step in data.StepsCollection.GroupBy(step => step.GroupByIndexer))
                    {
                        if (step.First().SharedStep == false)
                        {
                            data.TestWorkItem.Actions.Add(data.TestWorkItem.CreateTestStep());
                            if (data.TestWorkItem != null)
                            {
                                (data.TestWorkItem.Actions[stepNumber] as ITestStep).Title =
                                    new ParameterizedString(step.First().Title);
                                (data.TestWorkItem.Actions[stepNumber] as ITestStep).ExpectedResult =
                                    new ParameterizedString(step.First().ExpectedResult);

                                if (step.First().Attachment != null)
                                {
                                    try
                                    {
                                        foreach (ITestAttachment attachment in step.First().Attachment)
                                        {
                                            string filename = directoryName + "\\" + attachment.Name;
                                            attachment.DownloadToFile((filename));
                                            ITestAttachment file =
                                                (data.TestWorkItem.Actions[stepNumber] as ITestStep).CreateAttachment(
                                                    filename);
                                            file.Comment = attachment.Comment;
                                            (data.TestWorkItem.Actions[stepNumber] as ITestStep).Attachments.Add(file);
                                        }
                                    }
                                    catch
                                    {
                                        MessageBox.Show(
                                            @"A file attachment with the same name already exist or an error occurred while saving the attachments." +
                                            Environment.NewLine +
                                            @"Saving NOT will continue, please remove the attachment or refresh the work item.");
                                        return data;
                                    }
                                }
                            }
                        }

                        if (step.First().SharedStep)
                        {
                            ISharedStepReference sharedRef = data.TestWorkItem.CreateSharedStepReference();
                            sharedRef.SharedStepId = step.First().SharedStepNumber;
                            data.TestWorkItem.Actions.Add(sharedRef);
                        }
                        stepNumber++;
                    }

                    while (stepNumber < data.TestWorkItem.Actions.Count)
                        data.TestWorkItem.Actions.RemoveAt(stepNumber);

                    data.TestWorkItem.Save();
                    Directory.Delete(directoryName, true);
                    data = LoadData.LoadGridViewData(data);
                    MessageBox.Show(@"Saved Test Case " + data.WorkItemAttributes.Name + @" successful.",
                                    @"Work Item Saved");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
            return data;
        }
    }
}